package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.PageRes;
import com.example.demo.bean.log.SysLoginLogDO;
import com.example.demo.bean.log.SysOperLogDO;
import com.example.demo.convert.SysOperLogConvert;
import com.example.demo.dto.log.SysLoginLogPageReqVO;
import com.example.demo.dto.log.SysOperLogPageReqVO;
import com.example.demo.dto.log.SysOperLogRepVO;
import com.example.demo.exception.OtherException;
import com.example.demo.mapper.log.SysLoginLogMapper;
import com.example.demo.mapper.log.SysOperLogMapper;
import com.example.demo.service.ISysLoginLogService;
import com.example.demo.service.ISysOperLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

@Service
@Slf4j
public class SysOperLogServiceImpl extends ServiceImpl<SysOperLogMapper, SysOperLogDO> implements ISysOperLogService {

    @Resource
    private SysOperLogMapper sysOperLogMapper;

    @Override
    public PageRes<SysOperLogRepVO> list(SysOperLogPageReqVO sysOperLogPageReqVO) {
        PageRes<SysOperLogDO> pageResSource = sysOperLogMapper.selectPage(sysOperLogPageReqVO);
        PageRes<SysOperLogRepVO> pageResult = new PageRes<>();
        pageResult.setTotal(pageResSource.getTotal());
        pageResult.setList(pageResSource.getList().stream()
                .map(SysOperLogConvert.INSTANCE::convert)
                .collect(Collectors.toList()));
        return pageResult;
    }

    @Override
    public void addSysOperLog(SysOperLogDO sysOperLogDO) {
        sysOperLogMapper.insert(sysOperLogDO);
    }

    @Override
    public int deleteOperLog(Long[] logIds) {
        int deleteCount = 0;
        for (Long logId : logIds) {
            validExist(logId);
            deleteCount += sysOperLogMapper.deleteById(logId);
        }
        return deleteCount;
    }

    @Override
    public SysOperLogDO getSysOperLog(SysOperLogDO sysOperLogDO) {
        validExist(sysOperLogDO.getOperId());
        return sysOperLogMapper.selectById(sysOperLogDO.getOperId());
    }

    @Override
    public void clearOperLog() {
        sysOperLogMapper.delete(new QueryWrapper<>());
    }

    private void validExist(Long logId) {
        SysOperLogDO exist = sysOperLogMapper.selectById(logId);
        if (exist == null) {
            throw new OtherException("操作日志不存在");
        }
    }
}
